package com.jbp.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jbp.dao.UserLevelDao;
import com.jbp.model.User;
import com.jbp.model.UserLevel;
import com.jbp.service.UserLevelService;
import com.jbp.service.UserService;
import com.jbp.utils.LevelUtil;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jbp.utils.PageUtils;
import com.jbp.utils.Query;

import java.util.Date;
import java.util.Map;

/**
 * 用户等级(UserLevel)表服务实现类
 * @author cc
 * @since 2021-08-12 11:57:34
 */
@Service
public class UserLevelServiceImpl extends ServiceImpl<UserLevelDao, UserLevel> implements UserLevelService {

    @Autowired
    private UserService userService;

    @Override
    public int getExperience(Integer userId) {
        UserLevel userLevel = getByUserId(userId);
        return userLevel==null ? 0 : userLevel.getScore();
    }

    @Override
    public UserLevel getByUserId(Integer userId) {
        QueryWrapper<UserLevel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        return getOne(queryWrapper);
    }

    @Override
    public void addScore(Integer userId, int score) {
        UserLevel userLevel = getByUserId(userId);
        if (userLevel==null) {
            userLevel = new UserLevel();
            userLevel.setUserId(userId);
            userLevel.setScore(0);
            save(userLevel);
        }

        userLevel.setScore(userLevel.getScore()+score);
        userLevel.setLevel(LevelUtil.getLevel(userLevel.getScore()));
        userLevel.setUpdateTime(new Date());
        updateById(userLevel);

        User user = userService.getById(userId);
        if (user.getLevel()<userLevel.getLevel()) {
            user.setLevel(userLevel.getLevel());
            user.setUpdateTime(new Date());
            userService.updateById(user);
        }
    }

    @Override
    public boolean levelOn(Integer userId) {
        UserLevel userLevel = getByUserId(userId);
        if (userLevel!=null && DateUtils.addDays(userLevel.getUpdateTime(), 15).compareTo(new Date()) > 0) {
            return true;
        }
        return false;
    }
}